<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <!-- 警示提示框 -->
        <el-col>
          <el-alert
            title="只允许选择三级分类属性"
            type="warning"
            :closable="false"
            show-icon
          >
          </el-alert>
        </el-col>
        <!-- 级联选择器 -->
        <el-col>
          <el-form>
            <el-form-item label="选着商品分类: ">
              <!-- options所绑定的数据源 -->
              <!-- props是配置对象 -->
              <el-cascader
                props.expandTrigger="hover"
                :options="paramsCateList"
                v-model="paramsSelectedOptions"
                :props="catePropsObj"
                @change="handleChange"
              >
              </el-cascader>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <!-- tag切换 -->
      <el-tabs
        v-model="paramsActiveName"
        @tab-click="paramsHandleClick"
      >
        <!-- 动态参数 -->
        <el-tab-pane
          label="动态参数"
          name="many"
        >
          <el-row>
            <el-col>
              <el-button
                type="primary"
                :disabled="isDisableBtn"
                @click="addManyParams"
              >添加参数</el-button>
            </el-col>
          </el-row>
          <!-- table数据 -->
          <el-table
            :data="manyParamsList"
            stripe
            border
            style="width: 100%"
          >
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(tag_vals,i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close='handleClosed(i, scope.row)'
                >
                  {{ tag_vals }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInputRef"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#"
            > </el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            >
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="
                    editParamsDialog(scope.row.attr_id, scope.row.attr_name)
                  "
                >编辑</el-button>
                <!-- 删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteManyParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态参数 -->
        <el-tab-pane
          label="静态属性"
          name="only"
        >
          <el-row>
            <el-col>
              <el-button
                type="primary"
                :disabled="isDisableBtn"
                @click="addOnlyParams"
              >添加属性</el-button>
            </el-col>
          </el-row>
          <!-- table数据 -->
          <el-table
            :data="onlyParamsList"
            stripe
            border
            style="width: 100%"
          >
            <!-- 展开列 -->
            <!-- <el-table-column type="expand"> </el-table-column> -->
            <el-table-column
              type="index"
              label="#"
            > </el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            >
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="
                    editParamsDialog(scope.row.attr_id, scope.row.attr_name)
                  "
                >编辑</el-button>
                <!-- 删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteManyParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加参数对话框 -->
      <el-dialog
        :title="'添加' + setDilTextTitle"
        :visible.sync="addParamsdialogVisible"
        width="50%"
        @close="clearAddFormInfo"
      >
        <el-form
          ref="addParamsFormRef"
          :model="addParamsForm"
          label-width="120px"
          :rules="addParamsRules"
        >
          <el-form-item
            :label="setDilTextTitle + '名称: '"
            prop="attr_name"
          >
            <el-input v-model="addParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="addParamsdialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="addParams"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改参数弹出对话框 -->
      <el-dialog
        :title="'修改' + setDilTextTitle"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="clearAddFormInfo"
      >
        <el-form
          ref="addParamsFormRef"
          :model="addParamsForm"
          label-width="120px"
          :rules="addParamsRules"
        >
          <el-form-item
            :label="setDilTextTitle + '名称: '"
            prop="attr_name"
          >
            <el-input v-model="addParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="editParams"
          >确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //级联选择器分类参数的数据
      paramsCateList: [],
      //分类商品选中的值
      paramsSelectedOptions: [],
      //级联选择器的配置对象
      catePropsObj: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //控制tab标签栏选中转态
      paramsActiveName: 'many',
      //动态参数数据
      manyParamsList: [],
      //静态属性数据
      onlyParamsList: [],
      //控制添加参数对话框弹出
      addParamsdialogVisible: false,
      //控制修改参数对话框
      editDialogVisible: false,
      //修改参数的id
      editParamsSkysId: '',
      //添加参数表单数据
      addParamsForm: {
        attr_name: ''
      },
      //验证规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, message: '长度在 2 到 无限 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    //定义是否启用按钮,返回一个布尔值
    isDisableBtn() {
      if (this.paramsSelectedOptions.length === 3) {
        return false
      } else {
        return true
      }
    },
    //获取当前级联选择器选中的id
    cateId() {
      if (this.paramsSelectedOptions.length === 3) {
        return this.paramsSelectedOptions[2]
      }
      return null
    },
    //动态设置对话框文本标题
    setDilTextTitle() {
      if (this.paramsActiveName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //tab变化触发
    paramsHandleClick() {
      //console.log(this.paramsActiveName)
      this.getparamsData()
    },
    //获取分类参数列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.paramsCateList = res.data
      //   console.log(this.paramsCateList)
    },
    // 级联选择器中发送变化,请求获取分类参数列表
    handleChange() {
      this.getparamsData()
    },
    //获取参数列表数据
    async getparamsData() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.paramsActiveName
          }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      //将字符串转换为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
        //控制输入显示
        item.inputVisible = false;
        //展开列的输入值
        item.inputValue = '';
      })
      //console.log(res.data)
      //判断是动态数据还是静态属性
      if (this.paramsActiveName === 'many') {
        this.manyParamsList = res.data
        //console.log(res.data)
      } else {
        this.onlyParamsList = res.data
      }
    },
    //添加参数
    addOnlyParams() {
      this.addParamsdialogVisible = true
    },
    addManyParams() {
      this.addParamsdialogVisible = true
    },
    //重置表单
    clearAddFormInfo() {
      this.$refs.addParamsFormRef.resetFields()
    },
    //添加参数名称
    addParams() {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.paramsActiveName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.addParamsdialogVisible = false
        this.getparamsData()
      })
    },
    //删除参数
    async deleteManyParams(id) {
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getparamsData()
    },
    //修改参数弹出对话框
    editParamsDialog(id, name) {
      this.editParamsSkysId = id
      this.addParamsForm.attr_name = name
      //console.log(name);
      this.editDialogVisible = true
    },
    //修改参数名称
    editParams() {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editParamsSkysId}`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.paramsActiveName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.editDialogVisible = false
        this.getparamsData()
      })
    },
    //展开列方法
   async handleInputConfirm(row) {
        let inputValue = row.inputValue;
        if (inputValue) {
          row.attr_vals.push(inputValue);
        }
        row.inputVisible = false;
        row.inputValue = '';
        //发起请求,保存到数据库
        const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals: row.attr_vals.join(' ')
        });
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg);
    },
    showInput(row) {
        row.inputVisible = true;
        // $nextTick方法是在页面渲染完成之后才会被调用
         this.$nextTick(_ => {
          this.$refs.saveTagInputRef.$refs.input.focus();
        });
    },
    //删除tag标签
    async handleClosed(index, row) {
       row.attr_vals.splice(row.attr_vals.indexOf(index), 1);
        const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${row.attr_id}`);
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg);
    }
  }
}
</script>
<style lang="less" scoped>
.el-col {
  margin-bottom: 10px;
}
.el-tag + .el-tag {
  margin-left: 10px;
  margin-bottom: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  margin-bottom: 10px;
  vertical-align: bottom;
}
</style>
